import java.util.Arrays;

public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;
    private static final double DEFAULT_LOAD_FACTOR = 0.75; // 负载因子

    public HashBuck() {
        this.array = new Node[8];
    }

    /**
     * 存放元素
     * @param key
     * @param val
     */
    public void put(int key, int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        Node cur = array[index];

        // 检查有没有相同的元素
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        // 没有头插
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if (loadFactor() >= DEFAULT_LOAD_FACTOR) {
            // 扩容 && 进行重新哈希
            resize();
        }
    }

    /**
     * 扩容
     * 哈希表扩容需要注意的问题：
     * 需要遍历数组的每个链表的每个节点，重新哈希到新的哈希表
     */
    private void resize() {
        Node[] temp = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % temp.length;
                cur.next = temp[index];
                temp[index] = cur;
                cur = curNext;
            }
        }
        array = temp;
    }

    private double loadFactor() {
        return usedSize*1.0/array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
